package com.danielagarza.app;

import java.util.List;
import java.util.concurrent.ExecutionException;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.danielagarza.app.modelos.Tweet;
import com.danielagarza.app.servicios.LeerJSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Twitter extends Fragment {

	private Typeface font;
	private ProgressBar pgbCargar;
	private TextView txtCargar;

	public Twitter() {

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View vista = inflater.inflate(R.layout.activity_twitter, container,
				false);
		ListView lv = (ListView) vista.findViewById(R.id.listView1);
		Boolean estaConectado = isNetworkAvailable();
		pgbCargar = (ProgressBar) vista.findViewById(R.id.pgsBarCargando);
		txtCargar = (TextView) vista.findViewById(R.id.txtNombre);
		if (estaConectado)
			try {
				CargarDatos t = new CargarDatos();
				t.execute();
				font = Typeface.createFromAsset(getActivity().getAssets(),
						"font2.ttf");
				Gson g = new Gson();
				List<Tweet> l = g.fromJson(t.get(),
						new TypeToken<List<Tweet>>() {
						}.getType());
				ItemCompraAdapter adapter = new ItemCompraAdapter(
						this.getActivity(), l);
				lv.setAdapter(adapter);

			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		pgbCargar.setVisibility(estaConectado ? View.INVISIBLE : View.VISIBLE);
		txtCargar.setVisibility(estaConectado ? View.INVISIBLE : View.VISIBLE);
		return vista;
	}

	private class CargarDatos extends AsyncTask<Void, Integer, String> {
		@Override
		protected String doInBackground(Void... arg0) {
			String valor = LeerJSON
					.leerJSON("http://api.twitter.com/1/statuses/user_timeline/DanielaGarzaM.json?count=15");
			return valor;
		}
	}

	public class ItemCompraAdapter extends BaseAdapter {
		protected Activity activity;
		protected List<Tweet> items;

		public ItemCompraAdapter(Activity activity, List<Tweet> items) {
			this.activity = activity;
			this.items = items;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return items.get(position);
		}

		@SuppressLint("ShowToast")
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View vi = convertView;

			if (convertView == null) {
				LayoutInflater inflater = (LayoutInflater) activity
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				vi = inflater.inflate(R.layout.tweet_layout, null);
			}

			final Tweet item = items.get(position);
			TextView nombre = (TextView) vi.findViewById(R.id.txtCargando);
			nombre.setText(item.text);
			nombre.setTypeface(font);

			TextView tipo = (TextView) vi.findViewById(R.id.textView2);
			tipo.setText(item.created_at);
			tipo.setTypeface(font);
			
			ImageView pajarito = (ImageView) vi.findViewById(R.id.imageView1);
			pajarito.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					try{
			    		   Intent tweetIntent = new Intent(Intent.ACTION_SEND);
			    		    tweetIntent.putExtra(Intent.EXTRA_TEXT,"@DanielaGarzaM "+ item.text);
			    		    tweetIntent.setType("text/plain");
			    		    startActivity(tweetIntent);
			    		    
			        }catch (ActivityNotFoundException ex){
			           Toast.makeText(getActivity(), "Debes de tener la aplicación de Twitter", Toast.LENGTH_SHORT).show();
			        }
					
				}
			});
			
			
			return vi;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) getActivity()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		}
		return false;
	}
}
